package com.ruoyi.common.utils;

import cn.hutool.core.lang.Assert;
import com.alipay.api.*;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ruoyi.common.utils.property.AliProperty;
import com.ruoyi.common.utils.property.WeChatProperty;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;

@Component
public class AlipayUtils {
    private static Logger logger = LoggerFactory.getLogger(AliProperty.class);
    private static  String  activeEnv = SpringUtils.getBean(AliProperty.class).getActiveEnv();
    private static  String  appId = SpringUtils.getBean(AliProperty.class).getAppId();
    private static  String  gatewayUrl = SpringUtils.getBean(AliProperty.class).getGatewayUrl();
    private static  String  privateKey = SpringUtils.getBean(AliProperty.class).getPrivateKey();
    private static  String  publicKey = SpringUtils.getBean(AliProperty.class).getPublicKey();
    private static  String  certPath = SpringUtils.getBean(AliProperty.class).getCertPath();
    private static  String  rootCertPath = SpringUtils.getBean(AliProperty.class).getRootCertPath();



    private AlipayClient alipayClient() throws AlipayApiException, FileNotFoundException {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(gatewayUrl);
        certAlipayRequest.setAppId(appId);
        certAlipayRequest.setPrivateKey(privateKey);
        certAlipayRequest.setFormat(AlipayConstants.FORMAT_JSON);
        certAlipayRequest.setCharset(AlipayConstants.CHARSET_UTF8);
        certAlipayRequest.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
        if (activeEnv.equals("local")) {
            certAlipayRequest.setAlipayPublicCertPath(ResourceUtils.getFile(publicKey).getPath());
            certAlipayRequest.setCertPath(ResourceUtils.getFile(certPath).getPath());
            certAlipayRequest.setRootCertPath(ResourceUtils.getFile(rootCertPath).getPath());
        } else {
            certAlipayRequest.setAlipayPublicCertContent(getCertContentByPath(publicKey));
            certAlipayRequest.setCertContent(getCertContentByPath(certPath));
            certAlipayRequest.setRootCertContent(getCertContentByPath(rootCertPath));
        }
        return new DefaultAlipayClient(certAlipayRequest);
    }

    //支付宝下单
    public String alipay_app(String boby, String orderNo, BigDecimal payMoney, String notifyUrl) {
        try {
            AlipayClient alipayClient = alipayClient();
            AlipayTradeAppPayRequest appRequest = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setSubject(boby);
            model.setOutTradeNo(orderNo);
            model.setTimeoutExpress("30m");
            model.setTotalAmount(payMoney.toString());
            model.setProductCode("QUICK_MSECURITY_PAY");
            appRequest.setBizModel(model);
            appRequest.setNotifyUrl(notifyUrl);
            AlipayTradeAppPayResponse appResponse = alipayClient.sdkExecute(appRequest);
            return appResponse.getBody();
        } catch (AlipayApiException e) {
            logger.error("支付宝下单异常" + e);
            Assert.isTrue(false, "支付宝下单失败");
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public String alipay_h5(String boby, String orderNo, BigDecimal payMoney, String notifyUrl) {
        try {
            AlipayClient alipayClient = alipayClient();
            AlipayTradeWapPayRequest appRequest = new AlipayTradeWapPayRequest();
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setSubject(boby);
            model.setOutTradeNo(orderNo);
            model.setTimeoutExpress("30m");
            model.setTotalAmount(payMoney.toString());
            model.setProductCode("QUICK_WAP_WAY");
            appRequest.setBizModel((AlipayObject)model);
            appRequest.setNotifyUrl(notifyUrl);
            AlipayTradeWapPayResponse appResponse = (AlipayTradeWapPayResponse)alipayClient.pageExecute((AlipayRequest)appRequest);
            return appResponse.getBody();
        } catch (AlipayApiException e) {
            Assert.isTrue(false, "支付宝下单失败");
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    //支付宝退款
    public AlipayTradeRefundResponse ali_refund(String orderNo, BigDecimal payMoney) {
        try {
            AlipayClient alipayClient = alipayClient();
            AlipayTradeRefundRequest alipayTradeCloseRequest = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
            alipayTradeRefundModel.setOutTradeNo(orderNo);
            alipayTradeRefundModel.setRefundAmount(payMoney.toString());
            alipayTradeRefundModel.setRefundReason("M全民榜退款");
            alipayTradeCloseRequest.setBizModel(alipayTradeRefundModel);
            AlipayTradeRefundResponse refundResponse = alipayClient.certificateExecute(alipayTradeCloseRequest);
            return refundResponse;
        } catch (AlipayApiException e) {
            logger.error("支付宝退款异常" + e);
            Assert.isTrue(false, "支付宝退款异常");
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    //支付宝提现
    public AlipayFundTransUniTransferResponse AlipayFundTransUniTransfer(String orderNo, String alipayLoginName, String realName, BigDecimal transferMoney) {
        try {
            AlipayClient alipayClient = alipayClient();
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            model.setOutBizNo(orderNo);
            model.setTransAmount(transferMoney.toString());
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            model.setBizScene("DIRECT_TRANSFER");
            model.setOrderTitle("M全民榜代发");
            Participant payeeInfo = new Participant();
            payeeInfo.setIdentity(alipayLoginName);
            payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
            payeeInfo.setName(realName);
            model.setPayeeInfo(payeeInfo);
            model.setRemark("金币提现");
            request.setBizModel(model);
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            return response;
        } catch (AlipayApiException e) {
            logger.error("支付宝提现异常" + e);
            Assert.isTrue(false, e.getErrMsg());
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String getCertContentByPath(String name) {
        InputStream inputStream = null;
        String content = null;
        try {
            inputStream = this.getClass().getClassLoader().getResourceAsStream(name);
            content = new String(FileCopyUtils.copyToByteArray(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

}

